/*
 * @Author: 徐建辰
 * @Date: 2022-02-14 14:55:32
 * @LastEditTime: 2022-02-15 14:55:56
 * @LastEditors: 徐建辰
 * @Description: 抽离购物车逻辑代码
 */
import {ref} from 'vue'
import {Dialog, Toast} from 'vant'
import useCartStore from '@/store/shopcart'
import {getShopCarts, addCart, modifyCart, deleteCartItem} from '@/service/shopcart'

export default function useShopcart(router) {
  const cartStore = useCartStore()
  const cartlist = ref([])
  const result = ref([])
  const checked = ref(false)
  const all = ref(false)
  const checkAll = ref(true)

  // 初始化购物车数据
  async function initShopCart() {
    Toast.loading({message: '正在获取', forbidClick: true})
    const {data} = await getShopCarts({pageNumber: 1})
    console.log(data);
    cartlist.value = data
    result.value = data.map(item => item.cartItemId)
    Toast.clear()
  }
  // 添加至购物车
  async function addShopcart(data) {
    const {resultCode, message} = await addCart(data)
    if (resultCode === 200) {
      Toast.success('添加成功')
      cartStore.updateCart()
    }
    resultCode !== 200 && Toast.fail(message)
  }
  // 修改购物车数据
  async function modifyCartCount(value, {name}) {
    if (value > 5) {
      Toast.fail('超出单个商品的最大购买数量')
      return
    }
    if (value < 1) {
      Toast.fail('商品不得小于0')
      return
    }
    if (cartlist.value.filter(i => i.cartItemId == name)[0].goodsCount == value) return
    Toast.loading({message: '修改中...', forbidClick: true})
    await modifyCart({cartItemId: name, goodsCount: value})
    cartlist.value.forEach(item => {
      if (item.cartItemId == name) {
        item.goodsCount = value
      }
    })
    Toast.clear()
  }
  // 删除单个购物车数据
  function deleteItem(id) {
    Dialog.confirm({
      title: '温馨提示！',
      message: '确定要从购物车中删除此商品吗？',
    }).then(async () => {
      const {resultCode, message} = await deleteCartItem(id)
      if (resultCode !== 200) {
        Toast.fail(message)
        return
      }
      Toast.success('删除成功')
      initShopCart()
    })
  }
  // 单个商品选择操作
  function groupChange(result) {
    console.log(result);
    if (result.length == cartlist.value.length) {
      checkAll.value = true
    } else {
      checkAll.value = false
    }
    result.value = result
  }
  // 全选、反选操作
  function hanleAllCheck() {
    if (!checkAll.value) {
      result.value = cartlist.value.map(i => i.cartItemId)
    } else {
      result.value = []
    }
  }
  // 结算
  function onSubmit() {
    const resultVal = result.value
    if (!resultVal.length) {
      Toast.fail('请选择商品进行结算')
      return
    }
    const params = JSON.stringify(resultVal)
    router.push({path: 'createOrder', query: {cartItemIds: params}})
  }

  return {
    cartlist, result, checked, all, checkAll,
    initShopCart, addShopcart, modifyCartCount, deleteItem, 
    groupChange, hanleAllCheck, onSubmit
  }
}